package com.zsc.hospital.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zsc.hospital.mapper.OrderInfoMapper;
import com.zsc.hospital.mapper.ScheduleMapper;
import com.zsc.hospital.mapper.ScheduleRepository;
import com.zsc.hospital.model.OrderInfo;
import com.zsc.hospital.model.Patient;
import com.zsc.hospital.model.Schedule;
import com.zsc.hospital.service.HospitalService;
import com.zsc.hospital.util.ResultCodeEnum;
import com.zsc.hospital.util.YyghException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class HospitalServiceImpl implements HospitalService {

	@Autowired
	private ScheduleMapper hospitalMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private ScheduleRepository scheduleRepository;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> submitOrder(Map<String, Object> paramMap) {
        log.info(JSONObject.toJSONString(paramMap));
        String hoscode = (String)paramMap.get("hoscode");
        String depcode = (String)paramMap.get("depcode");
        String hosScheduleId = (String)paramMap.get("hosScheduleId");
        String reserveDate = (String)paramMap.get("reserveDate");
        String reserveTime = (String)paramMap.get("reserveTime");
        String amount = (String)paramMap.get("amount");

        Schedule schedule = this.getSchedule(hosScheduleId);
        System.out.println("scheduleid================="+hosScheduleId);
        System.out.println("schedule================="+schedule);
        System.out.println(schedule.getId());

        if(null == schedule) {
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }

        if(!schedule.getHoscode().equals(hoscode)
                || !schedule.getDepcode().equals(depcode)
                || !schedule.getAmount().toString().equals(amount)) {
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }

        //就诊人信息
        Patient patient = JSONObject.parseObject(JSONObject.toJSONString(paramMap), Patient.class);
        log.info(JSONObject.toJSONString(patient));
        //处理就诊人业务
        Long patientId = this.savePatient(patient);

        Map<String, Object> resultMap = new HashMap<>();

//        System.out.println("iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii  " +schedule.getAvailableNumber().intValue());

        int availableNumber = schedule.getAvailableNumber().intValue() - 1;

        com.zsc.yygh.model.hosp.Schedule scheduleVo = scheduleRepository.findById(hosScheduleId).get();
        scheduleVo.setAvailableNumber(scheduleVo.getAvailableNumber()-1);
        scheduleRepository.save(scheduleVo);



        System.out.println("======================可预约数据为：" + availableNumber +" ======================================");
        if(availableNumber > 0) {
            schedule.setAvailableNumber(availableNumber);

            System.out.println("======================订单信息：" + schedule +" ======================================");
            hospitalMapper.updateById(schedule);

            //记录预约记录
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setPatientId(patientId);

//            System.out.println("================================="+Long.parseLong("AAAA"));
            /**
             * 修改，类型转不过去
             */
//            orderInfo.setScheduleId(Long.parseLong(hosScheduleId));


            int number = schedule.getReservedNumber().intValue() - schedule.getAvailableNumber().intValue();


            orderInfo.setNumber(number);
            orderInfo.setAmount(new BigDecimal(amount));
            String fetchTime = "0".equals(reserveDate) ? " 09:30前" : " 14:00前";
            orderInfo.setFetchTime(reserveTime + fetchTime);
            orderInfo.setFetchAddress("一楼9号窗口");
            //默认 未支付
            orderInfo.setOrderStatus(0);
            orderInfoMapper.insert(orderInfo);

            resultMap.put("resultCode","0000");
            resultMap.put("resultMsg","预约成功");
            //预约记录唯一标识（医院预约记录主键）
            resultMap.put("hosRecordId", orderInfo.getId());
            //预约号序
            resultMap.put("number", number);
            //取号时间
            resultMap.put("fetchTime", reserveDate + "09:00前");;
            //取号地址
            resultMap.put("fetchAddress", "一层114窗口");;
            //排班可预约数
            resultMap.put("reservedNumber", schedule.getReservedNumber());
            //排班剩余预约数
            resultMap.put("availableNumber", schedule.getAvailableNumber());
        } else {
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }
        return resultMap;
    }

    @Override
    public void updatePayStatus(Map<String, Object> paramMap) {
        String hoscode = (String)paramMap.get("hoscode");
        String hosRecordId = (String)paramMap.get("hosRecordId");

        OrderInfo orderInfo = orderInfoMapper.selectById(hosRecordId);
        if(null == orderInfo) {
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }




        //已支付
        orderInfo.setOrderStatus(1);
        orderInfo.setPayTime(new Date());
        orderInfoMapper.updateById(orderInfo);
    }

    @Override
    public void updateCancelStatus(Map<String, Object> paramMap) {
        String hoscode = (String)paramMap.get("hoscode");
        String hosRecordId = (String)paramMap.get("hosRecordId");

        OrderInfo orderInfo = orderInfoMapper.selectById(hosRecordId);
        if(null == orderInfo) {
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }


        /**
         *修改========================================================================
         */
        String hosScheduleId = (String)paramMap.get("hosScheduleId");
        System.out.println("=======================hosScheduleId:"+hosScheduleId);
        Schedule schedule = this.getSchedule(hosScheduleId);
        int availableNumber = schedule.getAvailableNumber().intValue() + 1;
        com.zsc.yygh.model.hosp.Schedule scheduleVo = scheduleRepository.findById(hosScheduleId).get();
        scheduleVo.setAvailableNumber(scheduleVo.getAvailableNumber()+1);
        scheduleRepository.save(scheduleVo);
        schedule.setAvailableNumber(availableNumber);
        hospitalMapper.updateById(schedule);



        //已取消
        orderInfo.setOrderStatus(-1);
        orderInfo.setQuitTime(new Date());
        orderInfoMapper.updateById(orderInfo);
    }

    private Schedule getSchedule(String frontSchId) {
        System.out.println("=================mongo====="+scheduleRepository.findById(frontSchId).get().getWorkDate());
        com.zsc.yygh.model.hosp.Schedule scheduleVo = scheduleRepository.findById(frontSchId).get();
//        System.out.println("=================mongo====="+checkDate(scheduleRepository.findById(frontSchId).get().getWorkDate()));
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("docname",scheduleVo.getDocname());
        columnMap.put("skill",scheduleVo.getSkill());
        columnMap.put("work_date",checkDate(scheduleVo.getWorkDate()));
        columnMap.put("work_time",scheduleVo.getWorkTime());
        columnMap.put("status",scheduleVo.getStatus());
        columnMap.put("available_number",scheduleVo.getAvailableNumber());


//        System.out.println("================aaaaaaaaaa====="+hospitalMapper.selectByMap(columnMap).get(0));
//        return hospitalMapper.selectById(frontSchId);
//        return schedule;
        return hospitalMapper.selectByMap(columnMap).get(0);
    }

//    public Schedule checkSchedule(Schedule schedule , com.zsc.yygh.model.hosp.Schedule scheduleVo){
//        schedule.setHoscode(scheduleVo.getHoscode());
//        schedule.setDepcode(scheduleVo.getDepcode());
//        schedule.setTitle(scheduleVo.getTitle());
//        schedule.setDocname(scheduleVo.getDocname());
//        schedule.setSkill(scheduleVo.getSkill());
//        schedule.setWorkDate(checkDate(scheduleVo.getWorkDate()));
//        schedule.setWorkTime(scheduleVo.getWorkTime());
//        schedule.setReservedNumber(scheduleVo.getReservedNumber());
//        schedule.setAvailableNumber(scheduleVo.getAvailableNumber());
//        schedule.setAmount(scheduleVo.getAmount().toString());
//        schedule.setStatus(scheduleVo.getStatus());
//        return schedule;
//    }

    public static String checkDate(Date date){
        String format1 = null;
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            format1 = format.format(date);
        } catch (Exception e) {
        }
        return format1;
    }


    /**
     * 医院处理就诊人信息
     * @param patient
     */
    private Long savePatient(Patient patient) {
        // 业务：略
        return 1L;
    }

}
